let branchMenuData;
let currBranchId;

/**
 * 获取分支菜单
 * @param data 项目ID 分支ID isSupper
 * @param fun
 */
function getMenuByBranchId(data, fun) {
    $.ajax({
        url: listMenuByBranchIdUrl,
        type: "get",
        data: data,
        dataType: "json",
        async: false,
        error: ajaxError,
        success: function (data) {
            if (data.statusCode !== 200) {
                layer.msg(data.statusMsg);
                return;
            }
            fun(data.data);
        }
    });
}

/**
 * 加载菜单
 * @param currProject
 */
function loadMenu() {
    if (branchMenuData == null || currBranchId !== currProject.branchId) {
        //从新加载
        currBranchId = currProject.branchId;
        getMenuByBranchId({
            projectId: currProjectData.project.id,
            branchId: currBranchId,
            isSuper: currProjectData.project.remotePath == null ? 1 : 0
        }, data => {

            branchMenuData = data;
            setApi(branchMenuData.menuList);
        })
    }
}

//递归查询ID菜单
function findMenu(branchMenuData, id) {
    for (let m of branchMenuData) {
        if (m.id === id) {
            return m;
        }
        if (m.childrenMenu != null && m.childrenMenu.length !== 0) {
            let cm = findMenu(m.childrenMenu, id);
            if (cm != null) {
                return cm;
            }
        }
    }
}

//设置菜单API
function setApi(menuList) {
    $.each(menuList, (i, o) => {
        if (o.apiId != null) {
            o['api'] = branchMenuData.apiInfoList.find(api => api.id === o.apiId)
        }
        if (o.childrenMenu != null && o.childrenMenu.length !== 0) {
            setApi(o.childrenMenu);
        }
    });
}

/**
 * 渲染菜单
 */
function renderMenu() {
    //加载当前
    loadMenu();
    let currHeaderMenuId = getCurrHeaderMenuId(currProject.branchId);
    let menu = null;
    if (currHeaderMenuId != null) {
        menu = branchMenuData.menuList.find(i => i.id == currHeaderMenuId);
    }
    if (menu == null) {
        menu = branchMenuData.menuList[0];
        setCurrHeaderMenuId(currProject.branchId, menu.id);
    }
    //切换项目配置
    // let conf = currProjectData.projectConfig.find(i => i.menuName == menu.menuName) || {}
    // currProjectData.project.port = conf.port;
    // currProjectData.project.contextPath = conf.contextPath;

    let data = $.extend(currProjectData, branchMenuData, {currHeaderMenuId: menu.id});
    console.log(data);
    //渲染
    let headerTemplate = $("#headerTemplate").html();
    laytpl(headerTemplate).render(data, (html) => $("#header-body").html(html));
    // let menuTemplate = $("#menuTemplate").html();
    // laytpl(menuTemplate).render(data, (html) => $("#menu-body").html(html));
    let html = menuHtml(data);
    $("#menu-body").html(html)
    //事件
    element.render('nav', "");
    element.init();
}

//点击左边菜单在右边添加选项卡
function openTab(id) {
    setCurrMenuId(currProject.branchId, id)
    //去重复选项卡
    let $lapi = $('.api-tab-content');
    for (let i = 0; i < $lapi.length; i++) {
        if ($lapi.eq(i).attr('api-id') == id) {
            element.tabChange("api-tab", id);
            return;
        }
    }
    //添加选项卡
    let menu = findMenu(branchMenuData.menuList, id);
    //class 入参 字段 - 出参
    let typeArr = [];
    //from data 字段
    let formDataFields = [];
    for (let p of menu.api.apiParamList) {
        //引用数据类型
        if (p.classId != null) {
            let c = branchMenuData.classInfoList.find(i => i.id === p.classId);
            p.className = c.className;
            let res = classTypeArrJson.getTypeArrJson(c, p);
            //基本类型数组
            p.isBaseTypeArr = res.isBaseTypeArr;
            //添加当前类里面的所有数据类型
            typeArr = typeArr.concat(res.typeList);
        }
        //入参 不为JSON
        if (p.type == 1 && p.paramMode != ParamMode.json && (p.classId == null || p.isBaseTypeArr)) {
            formDataFields.push({
                paramName: p.paramName,
                paramDescribe: p.paramDescribe,
                type: p.isBaseTypeArr || p.dataType,
                paramMode: p.paramMode,
            });
        }
    }
    //class 字段
    for (let t of typeArr) {
        //入参 & 当前传参数非json
        if (t.type == 2 || t.paramMode == ParamMode.json || t.classFieldList == null) {
            continue;
        }
        formDataFields = formDataFields.concat(t.classFieldList);
    }
    let data = $.extend({typeList: typeArr}, menu, currProject, {
        projectList: projectData,
        envList: envData,
        formDataFields: formDataFields
    });
    console.log(data);
    let apiTemplate = $("#apiTemplate").html();
    laytpl(apiTemplate).render(data, html => {
        element.tabAdd("api-tab", {
            title: menu.menuName,
            content: html,
            id: id
        });
        // 切换选项卡
        element.tabChange("api-tab", id);
        form.render();
        //绑定切换环境事件
        envSelectHeaderData();
    });
}

//切换菜单
function switchMenu(t) {
    t = $(t).find('option:selected');
    let id = t.val();
    //设置当前菜单 刷新默认选择
    setCurrHeaderMenuId(currBranchId, id);
    //展示菜单
    $('#menu-div .layui-side').addClass('layui-hide').removeClass('layui-show');
    $('#menu-dev-' + id).removeClass('layui-hide').addClass("layui-show");
    //切换项目配置
    currProjectData.project.port = t.attr('data-port');
    currProjectData.project.contextPath = t.attr('data-contextPath');
}

/**
 * 切换
 */
function openSwitch() {
    // 切换项目 分支 环境
    //更新项目、环境数据
    getEnvAll(data => envData = data)
    projectAll(data => projectData = data);
    //合并数据渲染
    let data = $.extend({}, currProject, {projectList: projectData}, {envList: envData});
    console.log(data);
    let switchTemplate = $("#switchTemplate").html();
    laytpl(switchTemplate).render(data, html => {
        //弹框
        layer.open({
            title: '切换'
            , area: ['50%', '450px']
            , content: html
            , btn: ["提交"]
            , yes: function () {
                //获取表单内容
                let projectId = Number($('#switchForm [name=projectId]').val());
                let branchId = Number($('#switchForm [name=branchId]').val());
                let envId = Number($('#switchForm [name=envId]').val());

                //色泽当前项目 ID
                setCurrProject(projectId, branchId, envId);
                setCurrProjectData(currProject);

                //保存环境数据
                let envMap = {}
                currProjectData.env.headerMap = [];
                $('.env-id-' + envId + ' input').each((i, v) => {
                    let key = $(v).attr('key');
                    if (key != null) {
                        envMap[key] = v.value
                        currProjectData.env.headerMap.push(JSON.parse('{ "id":"' + key + '", "key":"' + v.name + '","value" : "' + v.value + '" }'));
                    }
                });
                setEnvMap(envMap);
                //渲染菜单 这里改为不刷新页面
                // location.reload();
                //显示菜单
                renderMenu();
                layer.closeAll();
            }
        });
        //渲染
        layui.form.render();
        //绑定联动
        form.on('select(projectIdFilter)', function (data) {
            let p = projectData.find(i => i.id == data.value);
            let $branch = $('[name="branchId"]');
            $branch.html("");
            $.each(p.branchList, (i, b) => {
                $branch.append("<option value=" + b.id + ">" + b.name + "</option>");
            });
            //渲染
            form.render('select');
        });
        form.on('select(envIdFilter)', function (data) {
            $('.env-div').addClass('layui-hide');
            $('.env-id-' + data.value).removeClass('layui-hide');
        });
    });

}

//更新当前API信息
function updateApi() {
    if(!currProjectData.project.remotePath){
        layer.msg("聚合项目更新还未开发完成，需切换具体项目进行更新");
        return;
    }
    pullProjectBranch(currProject.projectId, currProject.branchId);
}

//定位菜单
function positionMenu(id) {
    $('#menu-div .layui-nav-item').removeClass('layui-this');
    let $menu = $('.api-menu-' + id);
    $menu.addClass("layui-this").parents(".layui-nav-item").addClass("layui-nav-itemed");
    $menu.parents('.layui-side-scroll').animate({
        scrollTop: $menu.offset().top - 200
    }, 0);
}

//菜单过滤
function menuFilter(t) {
    let content = $(t).val();
    let $menu = $('#menu-div>div.layui-show');
    if (!content) {
        $menu.find('.layui-nav-item').removeClass('layui-hide');
        return;
    }
    let filterMenu = function (menus) {
        let isShow = false;
        for (let menu of menus) {
            let childrenShow = false;
            let child = $(menu).children('.layui-nav-child');
            if (child && child.length > 0) {
                //递归遍历子项
                childrenShow = filterMenu($(child).children('.layui-nav-item'));
                if (childrenShow) {
                    $(child).removeClass("layui-hide").addClass('layui-nav-itemed');
                }
            }
            //先移除上次的
            $(menu).removeClass("layui-hide");
            let txt = $(menu).children('a').data('describe');

            //当前满足||子项满足 就展示
            let mShow = inOf(txt, content) || childrenShow;
            if (!mShow) {
                $(menu).addClass("layui-hide");
            } else {
                $(menu).addClass('layui-nav-itemed');
            }
            //当前列表有一个true就返回给父true
            isShow = isShow || mShow;
        }
        return isShow;
    }
    //开始过滤
    filterMenu($menu.find(".layui-nav>.layui-nav-item"));
}

/**
 * 菜单
 * @param data
 * @return {string}
 */
function menuHtml(data) {
    //API菜单
    let apiMenu = function (menu) {
        let apiHtml = '';
        if (menu.api == null) {
            let describe = (menu.menuName + ' ' + menu.className ?? '');
            apiHtml +=
                '<a href="javascript:void(0);" title="' + describe + '" data-describe="' + describe + '">' +
                '    <cite> ' + (menu.menuName) + '</cite>' +
                '</a>';
        } else {
            let apiType = ApiType[menu.api.type];
            let describe = (menu.menuName + ' ' + menu.api.name + ' ' + menu.api.method + ' ' + apiType + ' ' + menu.api.path);
            apiHtml +=
                '<a href="javascript:openTab(' + (menu.id) + ');" style="height: auto;line-height: 24px;"' +
                '    data-describe="' + describe + '">' +
                '    <i class="fa fa-navicon" data-icon="fa-navicon"></i>' +
                '    <cite class="">' + (menu.menuName) + '</cite>' +
                '    <br/>' +
                '    <small class="api-type">' + apiType + '</small>' +
                '    <cite class="key_font">' + (menu.api.path) + '</cite>' +
                '</a>';
        }
        //子菜单
        if (menu.childrenMenu && menu.childrenMenu.length > 0) {
            apiHtml += '<dl class="layui-nav-child">';
            $.each(menu.childrenMenu, (j, cm) => {
                apiHtml += '<dd title="' + cm.menuName + (cm.api?" " + cm.api.path:'') + '" class="api-menu-' + cm.id + ' layui-nav-item" >';
                    // +' οnmοuseοver="showTips(this)" >';
                //递归调用自己
                apiHtml += apiMenu(cm);
                apiHtml += '</dd>'
            });
            apiHtml += '</dl>';
        }
        return apiHtml;
    }
    //菜单
    let div = '<div id="menu-div">';
    $.each(data.menuList, (i, menu) => {
        //第一层关联应用 select switchMenu()
        div +=
            '<div class="layui-side layui-bg-black ' + (menu.id != data.currHeaderMenuId ? 'layui-hide' : 'layui-show') + '"' +
            '     id="menu-dev-' + (menu.id) + '" title="' + (menu.menuName) + '">' +
            '    <div class="layui-side-scroll" lay-filter="side">' +
            '        <ul class="layui-nav layui-nav-tree  beg-navbar">';
        //第一层菜单
        $.each(menu.childrenMenu, (i1, menu1) => {
            div += '<li class="layui-nav-item">';
            //调用API菜单
            div += apiMenu(menu1);
            div += '</li>';
        });
        div += '        </ul>' +
            '    </div>' +
            '</div>';
    });
    div += '</div>';
    //菜单内容
    return div;
}

// function showTips(t) {
//     debugger
//     let row = "<span style='color: #0C0C0C'>" + $(t).attr('title') + "asdfasdfasdfasdfasdfasdf</span>"; //获取显示内容
//     //小tips
//     layer.tips(row, t, {
//         tips: [1, '#f2f2f2'],
//         maxWidth: 500
//     })
// }